package com.clei.utils;

import java.util.regex.Pattern;

/**
 * 证件号验证 util
 *
 * @author Y
 * @date 2022-10-14
 */
public final class CertificateCheckUtil {

    /**
     * 身份证号样式
     */
    private static final Pattern ID_NUMBER_PATTERN =
            Pattern.compile("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");

    private CertificateCheckUtil() {
    }

    /**
     * 身份证号校验
     *
     * @param idNumber 身份证号
     * @return 身份证号格式是否正确
     */
    public static boolean idNumberCheck(String idNumber) {
        int idNumberLength = 18;
        if (StringUtil.isBlank(idNumber)
                || idNumberLength != idNumber.length()
                || !ID_NUMBER_PATTERN.matcher(idNumber).matches()) {
            return false;
        }
        try {
            char[] idArr = idNumber.toCharArray();
            // 前十七位加权因子
            int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
            // 这是除以11后，可能产生的11位余数对应的验证码
            char[] lastCharArr = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

            int sum = 0;
            for (int i = 0; i < idCardWi.length; i++) {
                int current = idArr[i] - '0';
                int count = current * idCardWi[i];
                sum += count;
            }
            int modIndex = sum % 11;
            // 最后一位校验数是否正确
            return lastCharArr[modIndex] == idArr[idArr.length - 1];
        } catch (Exception e) {
            PrintUtil.log("身份证号验证出错 idNumber : {}", idNumber, e);
            return false;
        }
    }
}
